import axios from 'axios'
import stores from '@/store/index.js'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'

axios.defaults.headers.common['lastIp'] = sessionStorage.getItem("Ip")

var instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
})


instance.interceptors.request.use(
  config => {
    config.headers.common['token'] = store.state.user.token
    return config
  },
  error => {
    Message({ message: error.msg, type: 'error', duration: 5 * 1000 })
    return error
  }
)

// response interceptor
instance.interceptors.response.use(
  response => {
    const res = response.data
    stores.commit('user/SET_PROGRESS', 0)
    if (res.code === 201 || res.code === 400) {//默认不弹窗
      return Promise.reject(res)
    }
    //如果自定义代码不是200，就会被判定为错误。
    if (res.code !== 200) {
      Message({ message: res.msg || 'Error', type: 'error', duration: 5 * 1000, customClass: 'mzindex' })
      if (res.code === 10200) {
        MessageBox.confirm('您已经登出，您可以取消停留在此页面，或再次登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject(res)
    } else {
      // if (getToken()) {
      //   axios.defaults.headers.common['userId'] = getToken()
      // }
      axios.defaults.headers.common['userId'] = localStorage.getItem('ID')
      return res
    }
  },
  error => {
    Message({ message: error.msg, type: 'error', duration: 5 * 1000, customClass: 'mzindex' })
    stores.commit('user/SET_PROGRESS', 0)
    return Promise.reject(error)
  }
)
/**
 * 使用es6的export default导出了一个函数，导出的函数代替axios去帮我们请求数据，
 * 函数的参数及返回值如下：
 * @param {String} method  请求的方法：get、post、delete、put
 * @param {String} url     请求的url:
 * @param {Object} data    请求的参数
 * @returns {Promise}     返回一个promise对象，其实就相当于axios请求数据的返回值
 */
// export default function (method, url, data = null) {
//   method = method.toLowerCase();
//   if (method == 'post') {
//     return instance.post(url, data,{
//       onUploadProgress: progressEvent => {//进度条
//           let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
//           stores.commit('user/SET_PROGRESS', Math.floor(complete))
//       }
//   })
//   } else if (method == 'get') {
//     return instance.get(url, {
//       params: data
//     })
//   } else if (method == 'delete') {
//     return instance.delete(url, {
//       params: data
//     })
//   } else if (method == 'put') {
//     return instance.put(url, data)
//   } else {
//     return false
//   }
// }

export default function (method, url, data = null) {
  method = method.toLowerCase();

  // 开发环境下注入调试参数
  const debugParams = process.env.NODE_ENV === 'development' ? {
    XDEBUG_SESSION_START: 'PHPSTORM'
  } : {};
  if (method === 'get' || method === 'delete') {
    return instance[method](url, {
      params: {
        ...data,
        ...debugParams
      }
    });
  } else if (method === 'post' || method === 'put') {
    // 直接附加到 URL（兼容性更好）
    const separator = url.includes('?') ? '&' : '?';
    const debugUrl = process.env.NODE_ENV === 'development'
      ? `${url}${separator}XDEBUG_SESSION_START=PHPSTORM`
      : url;

    return instance[method](debugUrl, data, {
      onUploadProgress: progressEvent => {
        const complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
        stores.commit('user/SET_PROGRESS', Math.floor(complete));
      }
    });
  } else {
    return false;
  }
}
